﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using DevExpress.XtraGrid;
using System.Data.OracleClient;

namespace XmlAppliction
{
    public partial class GridForm : Form
    {
        string tjID; 
        string doSql;
        string GridSqlFromateStr = "";
        string stime;
        string etime;
        XMLToWordLib.DBLinkUser linkUser = new XMLToWordLib.DBLinkUser();
        private DataSet ds;
        Form1 _parentMgr;
        public GridForm(string tjid  , Form1 parentMgr)
        {

            this.tjID = tjid;
            this._parentMgr = parentMgr;

            this.stime = ((DateTime)_parentMgr.bar_EDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)_parentMgr.bar_ETimeEdit.EditValue).ToShortDateString();
            this.etime = ((DateTime)_parentMgr.bar_SDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)_parentMgr.bar_STimeEdit.EditValue).ToShortDateString(); 
                
            //this.stime = string.Format("{0} {1}", _parentMgr.bar_SDateEdit.Text, _parentMgr.bar_STimeEdit.Text);
            //this.startTime = string.Format("{0} {1}", _parentMgr.bar_EDateEdit.Text, _parentMgr.bar_ETimeEdit.Text);
            
            try
            {
                InitializeComponent();

                //设置导出菜单位置
                this.bar2.CanDockStyle = DevExpress.XtraBars.BarCanDockStyle.Bottom;
                this.bar2.DockStyle = DevExpress.XtraBars.BarDockStyle.Bottom; 
                this.barManager1.StatusBar = this.bar2;


                initBase();
                UpGrid();
            }
            catch (Exception ex)
            {
                throw new Exception ("数据库错误（" + ex.Message+")" ); 
            }
        }

        public GridForm(string tjid, string stime,string etime)
        {
            this.stime = stime;
            this.etime = etime;
            this.tjID = tjid; 

            try
            {
                InitializeComponent();
                //设置导出菜单位置
                this.bar2.CanDockStyle = DevExpress.XtraBars.BarCanDockStyle.All;
                this.bar2.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
                this.barManager1.MainMenu = this.bar2;



                initBase();
                UpGrid();
            }
            catch (Exception ex)
            {
                throw new Exception("数据库错误（" + ex.Message + ")");
            }
        }

        void initBase()
        {


            DataSet baseds = DBMgr.DbHelperOra.Query("select    t.明细参数,t.明细参数编号,t.统计项编号, t.统计项名称,t.执行语句,t.统计描述,t.连接参数编号,t.连接参数 from v_tj_tjx t where t.统计项编号 ='" + tjID + "'"); 

            if(baseds !=null  && baseds.Tables.Count>0  && baseds.Tables[0].Rows.Count >0)
            {
                DataRow row =baseds.Tables[0].Rows[0];
                doSql = row["执行语句"].ToString().Trim();
                this.Text = row["统计项名称"].ToString();
                GridSqlFromateStr = row["明细参数"].ToString().Trim();
                
                linkUser.ConnectionString = row["连接参数"].ToString().Trim();
                linkUser.Id = row["连接参数编号"].ToString().Trim();
                linkUser.Name = row["连接参数编号"].ToString().Trim();

                linkUser.Start();

            }

        }
        public void UpGrid()
        {

            string sql = "";
            int numCount = 0;
            if (doSql != null && doSql !="")
            {  
            //string nowTime = string.Format("{0}-{1}-{2} {3}:{4}:00", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute);
            //string befoTime = string.Format("{0}-{1}-{2} {3}:{4}:00", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day-7, DateTime.Now.Hour, DateTime.Now.Minute);

                string nowTime = this.etime;
                string befoTime = this.stime; 
                 
                
                try
                {

                    #region 如果清单数据量过大则不显示数据
                    sql =string.Format(doSql,befoTime,nowTime);
                    numCount = Convert.ToInt32(linkUser.GetTJNum(sql));
                    if (GridSqlFromateStr == "NONE" || numCount > 30000)
                    {
                        this.Text = "无权查看清单";
                        linkUser.Connection.Close();
                        linkUser.Close();
                        return;
                    }
                    else
                    { 
                        this.Text +="("+numCount+")";
                    }
                    #endregion

                    #region 链接数据库 填充数据
                    if (ds != null) ds.Dispose();

                    sql = GetGridSql(GridSqlFromateStr, sql);  
                    ds = new DataSet();

                    try
                    {
                        OracleDataAdapter command = new OracleDataAdapter(sql, linkUser.Connection);
                        command.Fill(ds, "DataSet");
                    }
                    catch
                    {
                        this.Text = "无权查看清单（代码:02001）";
                        return;
                    }
                    #endregion

                    #region 绑定到GridView
                    this.gridControl1.DataSource = ds.Tables[0].DefaultView;
                    gridView1.BestFitColumns();//设置宽度自动调节能显示内容


                    //汇总行统计方式
                     gridView1.GroupFooterShowMode = DevExpress.XtraGrid.Views.Grid.GroupFooterShowMode.Hidden;
                     GridGroupSummaryItem item = new GridGroupSummaryItem();
                     // item.FieldName = "";
                     item.SummaryType = DevExpress.Data.SummaryItemType.Count;
                     gridView1.GroupSummary.Add(item);
                    #endregion
                }   
                finally
                {
                    if (linkUser != null) linkUser.Close();
                } 
            }
        }


        string GetGridSql(string forMateType,string formateSql)
        {
            int indexNum=  formateSql.IndexOf(')') + 1;
            string rtnStr="";
            switch (forMateType)
            {
                case "SELF":
                    rtnStr = " select * " + formateSql.Substring(indexNum, formateSql.Length - indexNum);
                    break;
                default:
                    rtnStr = " select  " + forMateType + " " + formateSql.Substring(indexNum, formateSql.Length - indexNum);
                    break;
            }

            return rtnStr;
        
        }

        public void WriteFileXML(string path)
        {
            ds.DataSetName = "rows";
            DataTable dt = ds.Tables[0];
            dt.TableName = "row";
            ds.Tables[0].WriteXml(path);
            MessageBox.Show("写XML成功！","成功");
        }


        private void barButtonItem1_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            saveFileDialog1.ShowDialog();
            string filepath = saveFileDialog1.FileName;
            if (File.Exists(filepath))
            {
                File.Delete(filepath);
            }
            if (filepath != "")
            {
                WriteFileXML(filepath);
            }
            
        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            saveFileDialog1.Filter = "Excel文件|*.xls";
            saveFileDialog1.ShowDialog();
            string filepath = saveFileDialog1.FileName;
            if (File.Exists(filepath))
            {
                File.Delete(filepath);
            }
            if (filepath != "")
            {
                try
                {
                    gridView1.ExportToXls(filepath);
                    MessageBox.Show("保存成功！","成功");
                }
                catch
                {
                    MessageBox.Show("保存失败，路径设置错误或权限不够！", "失败");
                }
            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {

        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {

        }
    }
}
